# -*- coding: utf-8 -*-
import json,time,sqlite3,MySQLdb,pingthread
import threading
from threading import Thread

from Queue import Queue
# config = json.load(open("config.txt",'r'))
# 从mysql的rnd表取ndip数据
def read_mysql():
	conn=MySQLdb.connect(host="172.16.100.31",user="root",passwd="admin",db="rainbow_3_0")
	cursor=conn.cursor()
	# cursor.execute("select dscfgnwipaddr from rnd order by dscfgnwipaddr desc limit 10")
	cursor.execute("select dscfgnwipaddr from rnd order by dscfgnwipaddr")
	nds=cursor.fetchall()
	cursor.close()
	conn.close()
	print len(nds)
	return nds
def read_sqlte3():
	conn=sqlite3.connect(r'lkt.db3')
	conn.text_factory = str
	nds=conn.execute("select ndip from rnd order by ndip").fetchall()
	conn.close()
	print len(nds)
	return nds
def write_sqlte3(nds,notalive):
	s=time.time()
	conn=sqlite3.connect(r'lkt.db3')
	conn.text_factory = str
	print "notalive",len(notalive)
	for x in nds:
		if x[0] in notalive:
			sql="update rnd set bAlive=0 where ndip='"+x[0]+"'"
			# print x[0]
		else:
			sql="update rnd set bAlive=1 where ndip='"+x[0]+"'"
		conn.execute(sql)
	conn.commit()
	conn.close()
	print time.time()-s
#具体的处理函数，负责处理单个任务
def do_somthing_using(arguments):
	bAlive=pingthread.do_one(arguments[0],1,64)
	# print bAlive
	if bAlive==None:
		l.append(arguments[0])

	
#这个是工作进程，负责不断从队列取数据并处理
def working():
	while True:
		arguments = q.get()
		do_somthing_using(arguments)
		q.task_done()
def icmp_pool(nds):
	s=time.time()
	#把JOBS排入队列
	for i in nds:
		q.put(i)
	#等待所有JOBS完成
	q.join()
	print time.time()-s
	return l
q = Queue()
#fork NUM个线程等待队列
NUM = 30
for i in range(NUM):
	t = Thread(target=working)
	t.setDaemon(True)
	t.start()
nds=read_mysql()
start=time.time()
while True:
	l=[]
	delaytime=time.time()
	config = json.load(open("config.txt",'r'))
	if time.time()-start>config["MySQL_Poll_Time"]*3600:
		nds=read_mysql()
		start=time.time()
		
	notalive = icmp_pool(nds)	
	print "threading:",threading.activeCount()
	write_sqlte3(nds,notalive)
	print "sleep icmp",config["ICMP_Poll_Time"]-(time.time()-delaytime)
	time.sleep(config["ICMP_Poll_Time"]-(time.time()-delaytime))
